package com.sso.shiro;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis的基础存储方式，此hash不一样，可以单独设置每一条数据的失效时间
 * @param <K>
 * @param <V>
 */
public class MyValueCache<K,V> implements Cache<K,V>,Serializable {
    private final String REDIS_SHIRO_CACHE = "shiro-cache:";
    private String cacheKey;
    private RedisTemplate<K, V> redisTemplate;
    private long globExpire = 60*60;

    public MyValueCache(String name, RedisTemplate client){
        this.cacheKey=this.REDIS_SHIRO_CACHE+name+":";
        this.redisTemplate = client;
    }
    @Override
    public V get(K key) throws CacheException {
        return redisTemplate.boundValueOps(getCacheKey(key)).get();
    }

    @Override
    public V put(K key, V value) throws CacheException {
        V old = get(key);
        redisTemplate.boundValueOps(getCacheKey(key)).set(value);
        redisTemplate.boundValueOps(getCacheKey(key)).expire(globExpire,TimeUnit.MINUTES);
        return old;
    }

    @Override
    public V remove(K key) throws CacheException {
        V old = get(key);
        redisTemplate.delete(getCacheKey(key));
        return old;
    }

    @Override
    public void clear() throws CacheException {
        redisTemplate.delete(keys());
    }

    @Override
    public int size() {
        return keys().size();
    }

    @Override
    public Set keys() {
        return redisTemplate.keys(getCacheKey("*"));
    }

    @Override
    public Collection values() {
        Set<K> set = keys();
        List list = new  LinkedList();
        for(K s :set){
            list.add(get(s));
        }
        return list;
    }

    private K getCacheKey(Object k){
        return (K) (this.cacheKey+k);
    }
}
